package cn.yt.hospital.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 杨涛
 * @date 2023/3/1 14:14
 */
@Component
@Slf4j
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("----------->进入拦截器<---------------");

        Cookie[] cookies = request.getCookies();
        System.out.println(cookies);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        if (cookies==null){
            System.out.println("进来了");
            log.debug("-------------------没有cookie");
            response.getWriter().write("cookie is null");
            return false;
        }
        String userid ="";
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals("userid")){
                log.debug("-----------------有cookie"+cookie.getValue());
                //放行
                userid = cookie.getValue();
            }
        }

        if (userid==null){
            response.getWriter().write("cookie is null");
            return false;
        }
//        请求头 获取token
//        String token = request.getHeader("token");
//        log.debug("--------------token"+token);
//        if (token==null){
//            response.getWriter().write("token is null");
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
